package com.xzx;

import org.junit.Test;

import java.lang.reflect.InvocationTargetException;
import java.sql.Connection;
import java.sql.Driver;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;

/**
* 
* @author xinzhixuan
* @date 2025/9/11 11:45
* @version 1.0
*/
public class GetConnection {

    /**
     * 获取数据库连接方式一
     */
    @Test
    public void test1() throws SQLException {
        Driver driver = new com.mysql.cj.jdbc.Driver();
        Properties properties = new Properties();
        properties.setProperty("user","root");
        properties.setProperty("password","Admin_111");
        Connection connection = driver.connect("jdbc:mysql://localhost:3306/jdbc", properties);
        System.out.println(connection);
    }

    /**
     * 获取数据库连接方式二
     * 使用反射
     */
    @Test
    public void test2() throws Exception {
        Class<?> clazz = Class.forName("com.mysql.cj.jdbc.Driver");
        Driver driver = (Driver) clazz.getDeclaredConstructor().newInstance();
        Properties properties = new Properties();
        properties.setProperty("user","root");
        properties.setProperty("password","Admin_111");
        Connection connection = driver.connect("jdbc:mysql://localhost:3306/jdbc", properties);
        System.out.println(connection);
    }

    /**
     * 获取数据库连接方式三
     * 使用DriverManager
     */
    @Test
    public void test3() throws Exception {
        Class<?> clazz = Class.forName("com.mysql.cj.jdbc.Driver");
        DriverManager.deregisterDriver((Driver) clazz.getDeclaredConstructor().newInstance());
        Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/jdbc", "root", "Admin_111");
        System.out.println(connection);
    }

    /**
     * 获取数据库连接方式4
     * com.mysql.cj.jdbc.Driver 中有静态代码块，所以Driver类一加载，会自动注册驱动到DriverManager中
     * 所以可以去掉显示的注入，并且可以减少一个Driver对象
     *
     */
    @Test
    public void test4() throws Exception {
        Class.forName("com.mysql.cj.jdbc.Driver");
        Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/jdbc", "root", "Admin_111");
        System.out.println(connection);
    }

    /**
     * 获取数据库连接方式5
     * 省略掉Class.forName("com.mysql.cj.jdbc.Driver") 也能使用的原因是sip机制
     * mysql-connector-j-8.4.0.jar!/META-INF/services/java.sql.Driver文件中配置了com.mysql.cj.jdbc.Driver
     * 所以可以省略掉Class.forName("com.mysql.cj.jdbc.Driver")
     * 但是这种方式遇到多个驱动时就会有问题
     */
    @Test
    public void test5() throws Exception {
        Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/jdbc", "root", "Admin_111");
        System.out.println(connection);
    }
}